#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author：albert time:2019/8/6
import  requests
from lxml import  etree
import  re
from urllib.request import urlretrieve
import  random
dict = {}
img_url = []
img = []

headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
def Total_label():
    response = requests.get('http://www.umei.cc/bizhitupian/').content
    html = etree.HTML(response)

    title = html.xpath("//div[@class='w850 l oh']//a/@title")
    url = html.xpath("//div[@class='w850 l oh']//a/@href")
    # 循环镶嵌将标题与url结合
    index = 0
    for i in title:
        dict[i] = url[index]
        index += 1
# for k, v in dict.items():
#     print(k , v)
# 抓取链接
def Grab(num):
    url = dict[num]
    # print(url)
    response = requests.get(url,headers=headers,timeout=3)
    # response.encoding = 'utf-8'
    text = response.content.decode('utf-8')
    html = etree.HTML(text)
    pages = html.xpath("//div[@class='NewPages']//ul/li//@href")[-1].split('.')[0]
    return (int(pages),url)

# 获取总页中所有分页的url
def get_paging(url,pages_n):
    urls = [url+'{}.htm'.format(i) for i in range(1,pages_n+1)]
    '''获取每个url下的图片链接'''
    for i in urls:
        response_time = requests.get(i, headers=headers, timeout=3)
        # response.encoding = 'utf-8'
        text = response_time.content.decode('utf-8')
        html = etree.HTML(text)
        jpg_url = html.xpath("//div[@class='TypeList']//a/@href")
        for i in jpg_url:
            img_url.append(i)
    img_To_obtain()
def img_To_obtain():
    '''图片获取'''
    # 图片链接 Xpath语法：//*[@id="ArticleId60"]/p/a/img/@src
    # print(img_url)
    for x in img_url:
        response = requests.get(x,headers=headers,timeout=3)
        text = response.content.decode('utf-8')
        html = etree.HTML(text)
        '''整站爬，分页，可以通过url进行判断
        if 页数2 == 网页状态404：
            只是一张图片
        该系列有分页
        '''
        page_f = html.xpath('//*[@id="ArticleId60"]/p/a/img/@src')
        for j in page_f:
            img.append(j)

def extract():
    '''随机获取一张图片'''
    IMAGE_URL = random.choice(img)
    The_suffix = IMAGE_URL.split('.')[3]
    urlretrieve(IMAGE_URL, './image/img1.{}'.format(The_suffix))


if __name__ == '__main__':
    print('================欢迎来到图片选择器v1.0=====================')
    print('''=====================提示信息=============================
                    1：电脑壁纸
                    2：手机壁纸
                    3.动态壁纸
                                。。。。
                    9：可爱壁纸
    ''')
    Total_label()
    num = str(input("请输入您的选择："))
    '''页数+标题url'''
    page_n,url = Grab(num)
    print('%s页数为：%s, url:%s'%(num,page_n,url))
    get_paging(url,page_n)
    extract()
